package cn.com.gridinfo.sooc.core.course.note;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jeremy.arad.Arad;
import com.jeremy.arad.utils.Log;
import com.jeremy.arad.utils.StringUtils;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocFragment;
import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.core.course.classes.bean.CourseDetailsInfo;
import cn.com.gridinfo.sooc.core.course.note.activity.WriteNoteActiivity;
import cn.com.gridinfo.sooc.core.course.note.adapter.NoteAdapter;
import cn.com.gridinfo.sooc.core.course.note.bean.Note;
import cn.com.gridinfo.sooc.core.course.note.common.CodeConst;
import cn.com.gridinfo.sooc.core.course.note.dao.CourseDao;
import cn.com.gridinfo.sooc.core.expand.callname.common.PageConst;
import cn.com.gridinfo.sooc.utils.MessageUtils;

/**
 * 课程——笔记界面  细分度：节级
 * Created by yingchunli on 2015/12/30.
 */
public class NoteFragment extends BaseSoocFragment {

    View view;//当前界面
    @InjectView(R.id.theme_benjie)
    TextView themeBenjie;//本节内容
    @InjectView(R.id.note_list)
    UltimateRecyclerView noteList;//列表

    //无数据页面
    @InjectView(R.id.ll_no_data)
    LinearLayout layoutNoData;
    @InjectView(R.id.iv_no_data)
    ImageView ivNoData;
    @InjectView(R.id.tv_no_data)
    TextView tvNoData;

    LinearLayoutManager linearLayoutManager;//布局管理器
    NoteAdapter adapter;//适配器
    @InjectView(R.id.bj_container)
    LinearLayout bjContainer;//笔记的区域
    private String kcid, pmlid, mlid, nrid, jname;//课程id,章id,节ID,素材ID,节名称
    //课程加密或锁定，笔记不可见，显示默认界面
    private int isAuth, isEncrypt, kcsd, select, kcls;//是否有权限（0：无权限，1有权限）；是否加密（ 0：未加密 1：已加密  ）,课程锁定（0：未锁定 1：已锁定）,课程加入（0：未加入 1：已加入）,制作人 (0 不是制作人 1是制作人)
    int maxLastPositon;//数据最后位置

    private int zanPosition = -1;
    private CourseDao dao;
    private final int INTENT_WRITENOTE = 1;//跳转到写笔记界面
    private final String ENCRYPT = "课程已加密，笔记待解密~";
    private final String KCSD = "课程未开放，笔记已被封印~";
    private final String NO_AUTH = "课程已设置权限，笔记未开放";
    private final String NO_DATA = "还没有笔记，快去发表吧！";
    private final String NO_DATA2 = "暂无笔记！";


    public static NoteFragment newInstance(CourseDetailsInfo courseInfo) {
        Bundle args = new Bundle();
        NoteFragment fragment = new NoteFragment();
        args.putSerializable("courseInfo", courseInfo);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.course_note, null);
        ButterKnife.inject(this, view);
        Arad.bus.register(this);
        noteList.showFloatingButtonView();
        noteList.displayCustomFloatingActionView(false);
        view.findViewById(R.id.floatingbutton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("floatingbtn  onClick");
                startActivityForResult(new Intent(getActivity(), WriteNoteActiivity.class)
                        .putExtra("kcid", kcid).putExtra("pmlid", pmlid)
                        .putExtra("mlid", mlid).putExtra("nrid", nrid)
                        .putExtra("jname", jname), INTENT_WRITENOTE);
            }
        });
        dao = new CourseDao(this);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        noteList.setLayoutManager(linearLayoutManager);
        //发送请求
        Log.d("笔记界面 kcid->" + kcid);
        CourseDetailsInfo courseInfo = (CourseDetailsInfo) getArguments().get("courseInfo");
        initView(courseInfo, true);
        return view;
    }

    /**
     * 更新课程信息
     *
     * @param courseInfo 课程信息
     */
    public void onEventMainThread(CourseDetailsInfo courseInfo) {
        initView(courseInfo, false);
    }

    private void initView(CourseDetailsInfo courseInfo, boolean isFirst) {
        int requestCode;
        if (isFirst) {
            requestCode = CodeConst.COURSE_GET_NOTELIST_FIRST;
        } else {
            requestCode = CodeConst.COURSE_GET_NOTELIST_PUSHDOWN;
        }
        //获取参数 课程详情记录
        kcid = courseInfo.getKcid();//课程ID
        pmlid = courseInfo.getCurrPmId();//章 id
        mlid = courseInfo.getCurrMlId();//节 id
        nrid = courseInfo.getCurrNrId();//内容 id
        jname = courseInfo.getCurrSubName();//节名称
        isAuth = courseInfo.getIsAuth();//是否有权限（0:无权限，1：有权限）
        isEncrypt = courseInfo.getIsEncrypt();//是否加密（ 0：未加密 1：已加密  ）
        kcsd = courseInfo.getKcsd();//课程锁定（0：未锁定 1：已锁定）
        select = courseInfo.getSelect();//课程加入（0：未加入 1：已加入）
        kcls = courseInfo.getKcls();//制作人 (0 不是制作人 1是制作人)
        //未开放
        if (kcsd == 1) {
            //课程锁定
            themeBenjie.setVisibility(View.GONE);
            bjContainer.setVisibility(View.GONE);
            noteList.displayCustomFloatingActionView(false);
            showNoData(KCSD);
        }
        //课程开放
        else {
            //课程老师
            if (kcls == 1) {
                //制作人
                loadData(requestCode);
            }
            //课程收费
            else if (Arad.preferences.getBoolean(LocalMark.IS_PAY.getName())&&courseInfo.getIs_charge().equals("1")){
                if (courseInfo.getIsBuy()==0||courseInfo.getIsBuy()==2){
                    //课程未购买
                    themeBenjie.setVisibility(View.GONE);
                    bjContainer.setVisibility(View.GONE);
                    noteList.displayCustomFloatingActionView(false);
                    showNoData(NO_DATA2);
                }else {
                    //课程购买
                    loadData(requestCode);
                }
            }
            //已加入
            else if (select == 1) {
                //已加入课程
                loadData(requestCode);
            }
            //未加入
            //有权限
            else if (isAuth == 1) {
                loadData(requestCode);
            }
            //无权限
            else if (isAuth == 0) {
                themeBenjie.setVisibility(View.GONE);
                bjContainer.setVisibility(View.GONE);
                noteList.displayCustomFloatingActionView(false);
                showNoData(NO_AUTH);
            }
            //没有自定义权限的情况，判断是否加密
            //加密
            else if (isEncrypt == 1) {
                themeBenjie.setVisibility(View.GONE);
                bjContainer.setVisibility(View.GONE);
                noteList.displayCustomFloatingActionView(false);
                showNoData(ENCRYPT);
            }
            //未加入，有权限，未加密
            else {
                loadData(requestCode);
            }
        }
    }

    /**
     * 加载数据
     */
    private void loadData(int requestCode) {
        if (StringUtils.isNull(mlid)) {
            //节id为空，显示无数据页面
            showNoData(NO_DATA2);
            themeBenjie.setVisibility(View.GONE);
            bjContainer.setVisibility(View.GONE);
            noteList.displayCustomFloatingActionView(false);
        } else {
            noteList.displayCustomFloatingActionView(true);
            themeBenjie.setVisibility(View.VISIBLE);
            bjContainer.setVisibility(View.VISIBLE);
            themeBenjie.setText(jname);
            //发送请求  获取列表数据
            PageConst.pageNo = 1;
            getData(kcid, mlid, requestCode);
            linearLayoutManager.scrollToPosition(0);
        }
    }

    /**
     * 显示无数据页面
     *
     * @param msg 要显示的提示信息
     */
    private void showNoData(String msg) {
        layoutNoData.setVisibility(View.VISIBLE);
        ivNoData.setImageResource(R.mipmap.ic_biji_no_data);
        tvNoData.setText(msg);
        noteList.showEmptyView();
    }

    /**
     * 从服务器端获取数据
     *
     * @param kcid        课程id
     * @param mlid        章id
     * @param requestCode 请求码
     */
    private void getData(String kcid, String mlid, int requestCode) {
        noteList.hideEmptyView();
        dao.getNote(kcid, mlid, PageConst.pageNo, PageConst.pageSize, requestCode);
    }

    /**
     * 初始化列表数据
     */
    private void initData() {

        if (dao.getNoteList().isEmpty() || dao.getNoteList().size() == 0) {
            showNoData(NO_DATA);
            themeBenjie.setVisibility(View.GONE);
            bjContainer.setVisibility(View.GONE);
        } else {
            noteList.hideEmptyView();
            adapter = new NoteAdapter(dao.getNoteList(), getActivity());
            noteList.setAdapter(adapter);
            noteList.enableLoadmore();
            noteList.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    //下拉刷新
                    PageConst.pageNo = 1;
                    getData(kcid, mlid, CodeConst.COURSE_GET_NOTELIST_PUSHDOWN);
                    linearLayoutManager.scrollToPosition(0);
                }
            });
            noteList.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
                @Override
                public void loadMore(final int itemsCount, final int maxLastVisiblePosition) {
                    if (itemsCount > (PageConst.pageSize - 1)) {
                        maxLastPositon = maxLastVisiblePosition;
                        ++PageConst.pageNo;
                        getData(kcid, mlid, CodeConst.COURSE_GET_NOTELIST_PULLUP);
                    } else {
                        //加载数据完成,没有更多数据,显示没有更多了
                        adapter.loadNoDataView();
                        linearLayoutManager.scrollToPositionWithOffset(maxLastVisiblePosition, -1);
                    }
                }
            });
            adapter.setmOnItemClickLitener(new NoteAdapter.OnItemClickListener() {
                @Override
                public void OnItemClick(View view, int position) {
                    //点赞
                    zanPosition = position;
                    Note note = adapter.getObject(position);
                    if (note.getIsdz() == 0) {
                        //点赞
                        dao.dianZan(note.getBjid(), "1", CodeConst.COURSE_NOTE_DIANZAN);
                    } else {
                        //取消点赞
                        dao.dianZan(note.getBjid(), "0", CodeConst.COURSE_NOTE_DIANZAN_CANCEL);
                    }
                }
            });
        }
    }

    /**
     * 笔记发表成功后回调
     *
     * @param requestCode
     * @param resultCode
     * @param data        <br>Edit by jieli on 2016/06/16.
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //刷新列表
        if (resultCode == Activity.RESULT_OK) {
            //课程未开放
            if (kcsd == 1) {
                //课程锁定
                themeBenjie.setVisibility(View.GONE);
                bjContainer.setVisibility(View.GONE);
                noteList.displayCustomFloatingActionView(false);
                showNoData(KCSD);
            } else {

                //课程老师
                if (kcls == 1) {
                    //制作人
                    loadData(CodeConst.COURSE_GET_NOTELIST_PUSHDOWN);
                }

                //已加入
                else if (select == 1) {
                    //已加入课程
                    loadData(CodeConst.COURSE_GET_NOTELIST_PUSHDOWN);
                }
                //未加入
                //有权限
                else if (isAuth == 1) {
                    loadData(CodeConst.COURSE_GET_NOTELIST_PUSHDOWN);
                }
                //无权限
                else if (isAuth == 0) {
                    themeBenjie.setVisibility(View.GONE);
                    bjContainer.setVisibility(View.GONE);
                    noteList.displayCustomFloatingActionView(false);
                    showNoData(NO_AUTH);
                }
                //没有自定义权限的情况，判断是否加密
                //加密
                else if (isEncrypt == 1) {
                    themeBenjie.setVisibility(View.GONE);
                    bjContainer.setVisibility(View.GONE);
                    noteList.displayCustomFloatingActionView(false);
                    showNoData(ENCRYPT);
                }
                //未加入，有权限，未加密
                else {
                    loadData(CodeConst.COURSE_GET_NOTELIST_PUSHDOWN);
                }
            }
        }
    }

    @Override
    public void onRequestSuccess(int requestCode) {
        try {
            //网络请求成功
            if (dao.getStatus().equals("0")) {
                switch (requestCode) {

                    //首次请求初始化列表数据
                    case CodeConst.COURSE_GET_NOTELIST_FIRST://获取列表数据
                        initData();//初始化列表数据
                        break;

                    //下拉刷新
                    case CodeConst.COURSE_GET_NOTELIST_PUSHDOWN:
                        if (dao.getNoteList() != null && !dao.getNoteList().isEmpty()) {
                            noteList.hideEmptyView();
                        } else {
                            //无数据处理
                            showNoData(NO_DATA);
                        }
                        if (adapter == null) {
                            initData();
                        } else {
                            noteList.setRefreshing(false);
                            //刷新数据
                            adapter.refresh(dao.getNoteList());
                            if (dao.getNoteList().size() > (PageConst.pageSize - 1))
                                //数据大于每页显示的条数,则加载更多数据
                                adapter.loadMoreDataView();
                            else {
                                //数据小于当前页的话则不显示加载更多,显示没有更多了
                                adapter.loadNoDataView();
                                linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                            }
                        }
                        break;

                    //上拉翻页
                    case CodeConst.COURSE_GET_NOTELIST_PULLUP:
                        if (dao.getNoteList() != null && !dao.getNoteList().isEmpty()) {
                            //加载更多
                            adapter.loadmore(dao.getNoteList());
                        } else {
                            //数据加载完成,没有更多数据,显示没有更多了
                            adapter.loadNoDataView();
                            //无数据则不显示下一页
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                        }
                        break;
                    case CodeConst.COURSE_NOTE_DIANZAN:
                        //点赞成功，更新数据
                        adapter.updateObject(zanPosition, 1);
                        break;
                    case CodeConst.COURSE_NOTE_DIANZAN_CANCEL:
                        adapter.updateObject(zanPosition, 0);
                        break;

                }
            } else {
                MessageUtils.showImageShortToast(getActivity(), dao.getStatusCode());
            }
        } catch (Exception e) {
            MessageUtils.showImageShortToast(getActivity(), "请求数据异常");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        Arad.bus.unregister(this);
    }
}